package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaoxiaode
 * @date 2021/9/28 21:50
 **/
@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient iArticleClient;


    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /*
    *
    * 自媒体文章审核
    * */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        // 查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews==null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl--文章不存在");
        }

        // 状态为未审核才执行
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            // 从自媒体文章中提取文本和图片
            Map<String,Object> textAndImages=getTextAndImages(wmNews);
            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("content"), wmNews);
            if(!isSensitive) return;
            // 审核文本内容
            boolean booText=textScan((String) textAndImages.get("content"),wmNews);
            if(!booText)return;
            // 审核图片
            boolean booImage=handleImagesScan((List<String>) textAndImages.get("images"),wmNews);
            if(!booImage)return ;
            // 成功保存app端文章数据
            ResponseResult responseResult = saveArticle(wmNews);

            if(!responseResult.getCode().equals(200)){
                throw   new RuntimeException("WmNewsAutoScanServiceImpl-文章审核失败");
            }
            wmNews.setArticleId((Long) responseResult.getData());
            updateByText(wmNews,(short)9,"审核成功");

        }

    }

    /*
    * 自管理的敏感词审核
    * */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() >0){
            updateByText(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }

    /*
    *
    * 保存app端文章数据
    * */
    private ResponseResult saveArticle(WmNews wmNews) {

        ArticleDto dto=new ArticleDto();
        // 拷贝属性
        BeanUtils.copyProperties(wmNews,dto);

        // 文章布局/频道/作者/文章id
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }

        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }

        if(wmNews.getArticleId() !=null){
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());

        ResponseResult result = iArticleClient.saveArticle(dto);

        return result;
    }

    /*
    * 审核图片
    * */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag=true;
        if(images==null || images.size()==0){
            return flag;
        }
        // 下载图片 minio
        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imagList=new ArrayList<>();

        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(bis);

                // 图片识别
                String ocr = tess4jClient.doOCR(bufferedImage);
                boolean boo = handleSensitiveScan(ocr, wmNews);
                if(!boo){
                    return boo;
                }
                imagList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 审核图片
        try {
            Map map = greenImageScan.imageScan(imagList);

                if(map!=null){
                    // 审核失败
                    if(map.get("suggestion").equals("block")){
                        flag=false;
                        updateByText(wmNews, (short) 2, "当前图片存在违规内容");
                    }
                    // 不确定,需要人工审核
                    if(map.get("suggestion").equals("review")){
                        flag=false;
                        updateByText(wmNews, (short) 3, "不确定图片性质,需要手动确认");
                }
                }
            } catch (Exception e) {
                flag=false;
                e.printStackTrace();
            }
        return flag;
    }

    /*
    * 审核文本内容
    * */
    private boolean textScan(String content, WmNews wmNews) {

        boolean flag=true;

        if((wmNews.getTitle()+"-"+content).length()==0){

            return flag;
        }

        try {
            Map map = greenTextScan.greeTextScan((wmNews.getTitle()+"-"+content));
            if(map!=null){
                // 审核失败
                if(map.get("suggestion").equals("block")){
                    flag=false;
                    updateByText(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                // 不确定,需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag=false;
                    updateByText(wmNews, (short) 3, "不确定文本性质,需要手动确认");
                }
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }
        return flag;
    }

    /*
    * 修改文章内容
    * */
    private  void updateByText(WmNews wmNews,  short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /*
    * 从自媒体文章中提取文本和图片
    * 提取文章的封面图片
    *
    * */
    private Map<String,Object> getTextAndImages(WmNews wmNews) {

        StringBuilder stringBuilder=new StringBuilder();
        List<String> images=new ArrayList<>();
         // 从自媒体内容中提取文本和图片
        if(StringUtils.isNotBlank(wmNews.getContent())) {
            /* content:
                        type:
                        images:
                        value: */
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                    log.info(stringBuilder.toString());
                }

                if (map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }
            // 提取文章的封面图片
            if (StringUtils.isNotBlank(wmNews.getImages())) {
                String[] split = wmNews.getImages().split(",");
                images.addAll(Arrays.asList(split));
            }
            // 构造返回
            Map<String,Object> retMap=new HashMap<>();
            retMap.put("content",stringBuilder.toString());
            retMap.put("images",images);
            return retMap;

    }
}
